package com.topisv.tms.rest.qimen.qmservice;

import java.io.StringWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXB;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.repository.EdiGoodsSkuDao;
import com.topisv.tms.repository.EdiOrderDao;
import com.topisv.tms.repository.EdiOrderItemDao;
import com.topisv.tms.repository.work.WorkOrderDao;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorderconfirm.DeliveryOrder;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorderconfirm.DeliveryOrderConfirm;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorderconfirm.Invoice;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorderconfirm.OrderLine;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorderconfirm.Package;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorderconfirm.PackageItem;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorderconfirm.PackageMaterial;
import com.topisv.tms.rest.qimen.qmsend.QmRequestSender;
import com.topisv.tms.rest.qimen.request.RequestMethodType;
import com.topisv.tms.rest.qimen.request.RequestParams;
import com.topisv.tms.utils.InitProperties;
import com.topisv.tms.utils.rule.TMSTransportRule;

/**
 * 出库单确认接口 create by gaohuan 2015-05-09
 * */
@Component
@Transactional(readOnly =  false)
public class DeliveryOrderConfirmService extends QmRequestSender<String>{
	private static final Logger logger = LoggerFactory.getLogger(DeliveryOrderConfirmService.class);

	@Autowired
	private EdiOrderDao ediOrderDao;
	
	@Autowired
	private EdiOrderItemDao ediOrderItemDao;
	
	@Autowired
	private WorkOrderDao workOrderDao;
	@Autowired
	private EdiGoodsSkuDao ediGoodsSkuDao;
	
	@Override
	public RequestParams setupParam(RequestParams sendParams) {
		Map<String,String> params = new HashMap<String,String>();
		params.put("method", RequestMethodType.DELIVERY_ORDER_CONFIRM.getType());
		params.put("format", InitProperties.get("qm.format"));
		params.put("app_key", InitProperties.get("regAppKey"));
		params.put("v", InitProperties.get("qm.v"));
		params.put("sign_method", InitProperties.get("qm.sign_method"));
		params.put("customerId", "");//暂未定
		sendParams.setSecret(InitProperties.get("regAppSecret"));
		sendParams.setParams(params);
		return sendParams;
}

	@Override
	public String execute(String orderno,RequestParams sendParams) {
		SimpleDateFormat formatS = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Map<String,EdiGoodsSku> cacheSku = new HashMap<String,EdiGoodsSku>();
		
		String sendXml = null;
		EdiOrder ediOrder = ediOrderDao.findByOrdeno(orderno);
		
		if(ediOrder == null){
			logger.info("ediOrder 为空");
			return null;
		}
		sendParams.getParams().put("customerId", ediOrder.getCustomerCode());
		
		DeliveryOrderConfirm deliveryOrderConfirm = new DeliveryOrderConfirm();
		
		logger.info("--设置DeliveryOrder");
		DeliveryOrder deliveryOrder = new DeliveryOrder();
		deliveryOrder.setDeliveryOrderCode(ediOrder.getCustomerOrdeno());
		deliveryOrder.setDeliveryOrderId(ediOrder.getOrdeno());
		deliveryOrder.setWarehouseCode(ediOrder.getWarehouseCode());
		deliveryOrder.setOrderType(ediOrder.getDeliveryOrderType());
		deliveryOrder.setStatus("DELIVERED");
		deliveryOrder.setOutBizCode(TMSTransportRule.generateByPreFixAndSuffix("QM","DOCS"));
		
		Date currDate = new Date();
		//暂时只支持一次发货完成
		deliveryOrder.setConfirmType(0);
		deliveryOrder.setOrderConfirmTime(formatS.format(currDate));
		deliveryOrder.setOperatorCode("");
		deliveryOrder.setOperatorName("");
		deliveryOrder.setOperateTime(formatS.format(currDate));
		
		List<Invoice> invoiceList = new ArrayList<Invoice>();
		Invoice invoice = new Invoice();
		invoice.setHeader(ediOrder.getInvoiceTitle());
		invoice.setAmount(ediOrder.getInvoiceAmount()==null?0D:ediOrder.getInvoiceAmount());
		
		WorkOrder workOrder = workOrderDao.findByOrder(ediOrder.getOrdeno());
		
		logger.info("------设置发票信息");
		invoice.setContent("");
		invoice.setCode("");
		invoice.setNumber(workOrder.getInvoiceNo());
		invoiceList.add(invoice);
		deliveryOrder.setInvoice(invoiceList);
		
		
		deliveryOrderConfirm.setDeliveryOrder(deliveryOrder);
		
		logger.info("--设置package");
		List<Package> pkgs = new ArrayList<Package>();
		Package pkg = new Package();
		
		pkg.setLogisticsCode(workOrder.getExpressCompany());
		pkg.setLogisticsName(workOrder.getExpressName());
		
		if("ebill".equals(workOrder.getBillType())){
			pkg.setExpressCode(workOrder.getEbillNo());

		}else {
			pkg.setExpressCode(workOrder.getExpressNo());
		}
		
		pkg.setPackageCode("");
		pkg.setLength(0);
		pkg.setWidth(0);
		pkg.setHeight(0);
		//change by huwenjun 回传重量，奇门以克为单位，需要转换成KG，保留3位小数
		DecimalFormat df = new DecimalFormat("#.###");
		double dwg = workOrder.getWeight() == null? new Double(0) : workOrder.getWeight().doubleValue();
		String wg = df.format(dwg / 1000);
		pkg.setWeight(Double.parseDouble(wg));
		pkg.setVolume(0);
		pkg.setInvoiceNo(workOrder.getInvoiceNo());
		
		logger.info("------设置PackageMaterial");
		List<PackageMaterial> materialList = new ArrayList<PackageMaterial>();
		PackageMaterial material = new PackageMaterial();
		material.setQuantity(0);
		material.setType("");
		materialList.add(material);
		
		pkg.setPackageMaterial(materialList);
		
		logger.info("------设置items");
		List<PackageItem> itemList = new ArrayList<PackageItem>();
		
		logger.info("------设置OrderLine");
		List<OrderLine> orderLines = new ArrayList<OrderLine>();
		List<EdiOrderItem> ediOrderItemList = ediOrderItemDao.findByOrdeno(ediOrder.getOrdeno());
		if(ediOrderItemList!=null){
			for (int i = 0; i < ediOrderItemList.size(); i++) {
				EdiOrderItem ediOrderItem = ediOrderItemList.get(i);		
				EdiGoodsSku ediGoodsSku = this.getEdiGoodsSku(ediOrder.getCustomerCode(), ediOrderItem.getSku(), cacheSku);
				if(ediGoodsSku==null){ediGoodsSku = new EdiGoodsSku();}
				
				PackageItem pi = new PackageItem();
				pi.setItemCode(ediGoodsSku.getBar());
				pi.setItemId(ediGoodsSku.getId()+"");
				pi.setQuantity(ediOrderItem.getQty()+"");
				itemList.add(pi);
				
				
				OrderLine orderLine = new OrderLine();
				orderLine.setOrderLineNo(ediOrderItem.getLineNo());
				orderLine.setOrderSourceCode(ediOrderItem.getSourceOrderCode());
				orderLine.setSubSourceCode(ediOrderItem.getSubSourceOrderCode());
				orderLine.setItemCode(ediGoodsSku.getBar());
				orderLine.setItemId(ediGoodsSku.getId()+"");
				orderLine.setOwnerCode(ediGoodsSku.getCustomerCode());
				orderLine.setItemName(ediGoodsSku.getSkuName());
				orderLine.setExtCode(ediOrderItem.getExtCode());
				orderLine.setPlanQty(ediOrderItem.getQty());
				orderLine.setActualQty(ediOrderItem.getQty());
				
				//--------------未处理
				orderLine.setBatchCode("");
				orderLine.setExpireDate("");
				orderLine.setProduceCode("");
				orderLines.add(orderLine);
			}
			
		}
		
		
		
		pkg.setItems(itemList);
		
		pkgs.add(pkg);
		
		
		
		deliveryOrderConfirm.setPkgs(pkgs);
		
		
		deliveryOrderConfirm.setOrderLines(orderLines);
		
		StringWriter writer = new StringWriter();
		JAXB.marshal(deliveryOrderConfirm,writer);
		sendXml = writer.toString();
		
		return sendXml;
	}
	

	public EdiGoodsSku getEdiGoodsSku(String customerCode,String sku,Map<String,EdiGoodsSku> cacheSku){
		EdiGoodsSku ediGoodsSku = null;
		if(cacheSku.get(customerCode+"_"+sku) != null){
			ediGoodsSku = cacheSku.get(customerCode+"_"+sku);
		}else {
			ediGoodsSku = ediGoodsSkuDao.findByCustomerCodeAndSku(customerCode ,sku);
		}
		return ediGoodsSku;
	}
	
}
